<template>
  <view class="container">
    <!-- 顶部导航 -->
    <uni-nav-bar title="预约详情" left-icon="back" @clickLeft="back"></uni-nav-bar>

    <!-- 科室信息 -->
    <view class="section">
      <view class="section-title">科室信息</view>
      <view class="department-info">
        <text class="dept-name">{{ clinicInfo.name }}</text>
      </view>
    </view>

    <!-- 医生选择 -->
    <view class="section">
      <view class="section-title">选择医生</view>
      <view class="doctor-list">
        <view v-for="(doctor, index) in doctors" :key="doctor.id" class="doctor-item"
          :class="{ active: selectedDoctor && selectedDoctor.id === doctor.id }" @click="selectDoctor(doctor)">
          <image class="doctor-avatar" :src="doctor.avatar || '/static/doctor.png'" mode="widthFix"></image>
          <view class="doctor-info">
            <text class="name">{{ doctor.doctor }}</text>
            <text class="title">{{ doctor.doctor_title }}</text>
          </view>
        </view>
        <view v-if="doctors.length === 0" class="no-doctor">
          该科室暂无医生出诊
        </view>
      </view>
    </view>

    <!-- 日期选择 -->
    <view class="section" v-if="selectedDoctor">
      <view class="section-title">选择日期</view>
      <scroll-view scroll-x class="date-scroll">
        <view v-for="(date, index) in dates" :key="index" class="date-item" :class="{
          active: selectedDate && selectedDate.value === date.value,
          disabled: !date.available
        }" @click="selectDate(date)">
          <text class="week">{{ date.week }}</text>
          <text class="month-day">{{ date.month }}月{{ date.day }}日</text>
          <text class="status" v-if="!date.available">约满</text>
        </view>
      </scroll-view>
    </view>

    <!-- 时间段选择 -->
    <view class="section" v-if="selectedDoctor && selectedDate">
      <view class="section-title">选择时间段</view>
      <view class="time-grid">
        <view v-for="(time, index) in timeSlots" :key="index" class="time-item" :class="{
          active: selectedTime && selectedTime.value === time.value,
          disabled: !time.available
        }" @click="selectTime(time)">
          {{ time.label }}
        </view>
      </view>
      <view class="time-note" v-if="timeSlots.length > 0 && !timeSlots.some(t => t.available)">
        该日期暂无可用时段，请选择其他日期
      </view>
      <view class="time-note" v-if="timeSlots.length === 0">
        加载中...
      </view>
    </view>

    <!-- 就诊人选择 -->
    <view class="section" v-if="selectedDoctor && selectedDate && selectedTime">
      <view class="section-title">选择就诊人</view>
      <view class="patient-list">
        <view v-for="(patient, index) in patients" :key="index" class="patient-item"
          :class="{ active: selectedPatient && selectedPatient.id === patient.id }" @click="selectPatient(patient)">
          <view class="patient-info">
            <text class="name">{{ patient.username }}</text>
            <text class="phone">{{ patient.phone }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-btn" @click="submitAppointment" :class="{ disabled: !canSubmit }">
      确认预约
    </view>
  </view>
</template>

<script>
import api from '../../api/index';

export default {
  data() {
    return {
      // 科室信息
      clinicInfo: {
        name: "",
        doctorCount: 0,
        available: true,
        id: ""
      },
      departmentName: '',     // 科室名称 - 避免在data()中引用this
      departmentId: '1',     // 科室ID - 避免在data()中引用this
      doctors: [
        { id: 1, doctor: '张医生', doctor_title: '主任医师', avatar:"https://preview.qiantucdn.com/58pic/nA/Vx/a4/Sk/pk25wynmjzg9h4ua3rsc6xe8ib10vfld_PIC2018.png!w1024_new_0_1"},
        { id: 2, doctor: '李医生', doctor_title: '副主任医师', avatar: "https://bpic.588ku.com/element_pic/25/07/03/05279667089c1cb2271aa1bd70f09011.jpg!/fw/350/quality/90/unsharp/true/compress/true" },
        { id: 3, doctor: '王医生', doctor_title: '主治医师', avatar: "https://imgs.699pic.com/images/402/570/352.jpg!detail.v1" }
      ],
      dates: [],
      timeSlots: [],
      patients: [],
      selectedDoctor: null,
      selectedDate: null,
      selectedTime: null,
      selectedPatient: null
    };
  },
  
  computed: {
    canSubmit() {
      return this.selectedDoctor && 
        this.selectedDate && 
        this.selectedTime && 
        this.selectedPatient;
    }
  },
  
  onLoad(options) {
    if (options.clinic) {
      const clinic = JSON.parse(decodeURIComponent(options.clinic));
      this.clinicInfo = clinic;
      // 优先使用department字段（与后端保持一致），如果没有则使用name字段，添加默认值
      this.departmentName = clinic.department || clinic.name || '未命名科室';
      this.departmentId = clinic.id || '1'; // 从上一个页面获取科室ID
      // 确保departmentName不为空时才调用API
      if (this.departmentName) {
        // 不再调用获取医生列表接口，直接使用本地数据
        this.updateDoctorsByDepartment(this.departmentName);
      } else {
        console.error('科室名称为空，使用默认科室数据');
        this.updateDoctorsByDepartment('未命名科室');
      }
    } else {
      // 如果没有传入clinic参数，使用默认科室信息
      this.departmentName = '未命名科室';
      this.departmentId = '1';
      this.updateDoctorsByDepartment('未命名科室');
    }
    this.dates = this.generateDates();
    // 默认选中今天
    if (this.dates.length > 0) {
      this.selectedDate = this.dates[0];
    }
    
    // 从本地存储获取就诊人信息
    this.getPatientsFromStorage();
  },
  
  methods: {
    back() {
      uni.navigateBack();
    },
    
    // 删除getDoctorsByDepartment方法
    
    updateDoctorsByDepartment(departmentName) {
      // 实现模拟数据生成逻辑，确保即使API请求失败也能显示医生列表
      this.doctors=[
        { id: 1, doctor: '张医生', doctor_title: '主任医师', avatar:"https://preview.qiantucdn.com/58pic/nA/Vx/a4/Sk/pk25wynmjzg9h4ua3rsc6xe8ib10vfld_PIC2018.png!w1024_new_0_1"},
        { id: 2, doctor: '李医生', doctor_title: '副主任医师', avatar: "https://bpic.588ku.com/element_pic/25/07/03/05279667089c1cb2271aa1bd70f09011.jpg!/fw/350/quality/90/unsharp/true/compress/true" },
        { id: 3, doctor: '王医生', doctor_title: '主治医师', avatar: "https://imgs.699pic.com/images/402/570/352.jpg!detail.v1" }
      ];
    },
    
    generateDates() {
      // 生成未来7天的日期列表
      const dates = [];
      const today = new Date();
      
      for (let i = 0; i < 7; i++) {
        const date = new Date();
        date.setDate(today.getDate() + i);
        
        const dayOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()];
        
        dates.push({
          value: date.toISOString().split('T')[0], // 格式：YYYY-MM-DD
          week: dayOfWeek,
          month: date.getMonth() + 1,
          day: date.getDate(),
          available: true // 默认所有日期都可预约
        });
      }
      
      return dates;
    },
    
    // 选择医生
    selectDoctor(doctor) {
      this.selectedDoctor = doctor;
      // 重置已选时间段
      this.selectedTime = null;
      // 生成时间段
      this.generateTimeSlots();
    },
    
    // 选择日期
    selectDate(date) {
      if (date.available) {
        this.selectedDate = date;
        this.selectedTime = null;
        if (this.selectedDoctor) {
          this.generateTimeSlots();
        }
      }
    },
    
    // 选择时间段
    selectTime(time) {
      if (time.available) {
        this.selectedTime = time;
      }
    },
    
    // 选择就诊人
    selectPatient(patient) {
      this.selectedPatient = patient;
    },
    
    // 生成时间段
    generateTimeSlots() {
      // 生成模拟的时间段数据
      this.timeSlots = [
        { value: 'morning', label: '9:00-12:00', available: true },
        { value: 'afternoon', label: '2:00-4:00', available: true },
        { value: 'evening', label: '4:00-5:00', available: true }
      ];
    },
    
    // 从本地存储获取就诊人信息
    getPatientsFromStorage() {
      try {
        // 直接获取userInfo，不进行JSON.parse，因为它可能已经是对象
        const userInfo = uni.getStorageSync('userInfo');
        // console.log('从本地存储获取到的userInfo:', userInfo);
        // console.log('userInfo类型:', typeof userInfo);
        
        // 检查userInfo是否存在且不为null/undefined
        if (userInfo) {
          // 规范化用户信息格式，确保有id、username和phone字段
          let normalizedUserInfo;
          
          if (typeof userInfo === 'object') {
            // 如果已经是对象，检查字段并规范化
            normalizedUserInfo = {
              id: userInfo.id || 'p1',
              username: userInfo.username || userInfo.name || '用户',
              phone: userInfo.phone || '13800138000'
            };
          } else if (typeof userInfo === 'string') {
            // 如果是字符串，尝试解析
            try {
              const parsedUserInfo = JSON.parse(userInfo);
              normalizedUserInfo = {
                id: parsedUserInfo.id || 'p1',
                username: parsedUserInfo.username || parsedUserInfo.name || '用户',
                phone: parsedUserInfo.phone || '13800138000'
              };
            } catch (parseError) {
              console.warn('解析字符串userInfo失败，使用默认数据:', parseError);
              normalizedUserInfo = {
                id: 'p1',
                username: '张小明',
                phone: '13800138001'
              };
            }
          } else {
            // 其他类型，使用默认数据
            console.warn('userInfo类型不符合预期，使用默认数据');
            normalizedUserInfo = {
              id: 'p1',
              username: '张小明',
              phone: '13800138001'
            };
          }
          
          this.patients = [normalizedUserInfo];
          
          // 默认选中第一个就诊人
          if (this.patients.length > 0) {
            this.selectedPatient = this.patients[0];
          }
        } else {
          // 如果本地存储没有数据，使用默认数据
          this.patients = [
            { id: 'p1', username: '张小明', phone: '13800138001' }
          ];
          this.selectedPatient = this.patients[0];
        }
      } catch (e) {
        console.error('获取本地存储数据失败:', e);
        // 异常情况下使用默认数据
        this.patients = [
          { id: 'p1', username: '张小明', phone: '13800138001' }
        ];
        this.selectedPatient = this.patients[0];
      }
    },
    
    // 修复：将submitAppointment方法正确放入methods对象中，并添加逗号
    submitAppointment() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '请完整填写预约信息',
          icon: 'none'
        });
        return;
      }

      // 准备预约数据 - 与后端模型字段严格匹配
      const appointmentData = {
        department: this.departmentName,
        doctor: this.selectedDoctor.doctor,
        doctor_title: this.selectedDoctor.doctor_title,
        doctor_id: this.selectedDoctor.id || 1,
        date: this.selectedDate.value,
        time: this.selectedTime.label,
        patient_name: this.selectedPatient.username, // 使用username而不是name
        patient_phone: this.selectedPatient.phone,
        clinic_id: this.departmentId,
        user_id: 1, // 实际应用中应从用户登录信息中获取
        status: 'pending' // 默认为待确认状态
        // created_at 和 updated_at 由后端自动生成
        // id 由后端自动生成
      };

      // 显示确认弹窗和提交逻辑
      uni.showModal({
        title: '确认预约',
        content: `科室：${this.departmentName}\n医生：${this.selectedDoctor.doctor} ${this.selectedDoctor.doctor_title}\n日期：${this.selectedDate.month}月${this.selectedDate.day}日\n时间：${this.selectedTime.label}\n就诊人：${this.selectedPatient.username}\n手机号：${this.selectedPatient.phone}`,
        success: (res) => {
          if (res.confirm) {
            // 模拟预约提交
            console.log('提交预约数据：', appointmentData);
            
            // 显示加载动画
            uni.showLoading({
              title: '提交预约中...',
              mask: true
            });
            // 使用API提交预约
            api.submitAppointment(appointmentData)
              .then(res => {
                // 隐藏加载动画
                // console.log(2222222222); 
                uni.hideLoading();
                
                if (res && res.code === 200) {
                  // 成功回调
                  uni.showToast({
                    title: '预约成功',
                    icon: 'success'
                  });

                  // 1秒后返回上一级页面
                  setTimeout(() => {
                    uni.navigateBack();
                  }, 1000);
                } else {
                  // 业务逻辑错误
                  uni.showToast({
                    title: res?.message || '预约失败，请稍后重试',
                    icon: 'none'
                  });
                }
              })
              .catch(err => {
                // 隐藏加载动画
                if (wx.hideLoading) {
                  wx.hideLoading();
                }
                
                // 异常处理
                console.error('预约请求异常:', err);
                uni.showToast({
                  title: '网络异常，请稍后重试',
                  icon: 'none'
                });
              });
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
  padding-bottom: 100rpx;
}

.section {
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  &-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;

    &::before {
      content: '';
      display: inline-block;
      width: 8rpx;
      height: 28rpx;
      background-color: #007aff;
      border-radius: 4rpx;
      margin-right: 12rpx;
    }
  }
}

.department-info {
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  
  .dept-name {
    font-size: 30rpx;
    color: #333;
    font-weight: 500;
    margin-right: 20rpx;
  }
  
  .doctor-count {
    font-size: 26rpx;
    color: #666;
  }
}

.doctor-list {
  .doctor-item {
    display: flex;
    align-items: center;
    padding: 20rpx;
    margin-bottom: 20rpx;
    border-radius: 8rpx;
    background: #f8f8f8;
    transition: all 0.3s;

    &:last-child {
      margin-bottom: 0;
    }

    &.active {
      background: #e3f2fd;
      border: 1rpx solid #007aff;
    }

    &-avatar {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      margin-right: 20rpx;
      border: 2rpx solid #eee;
    }

    &-info {
      flex: 1;
      display: flex;
      flex-direction: column;

      .name {
        font-size: 30rpx;
        color: #333;
        margin-bottom: 8rpx;
        font-weight: 500;
      }

      .title {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 5rpx;
      }

      .specialty {
        font-size: 22rpx;
        color: #888;
      }
    }
  }

  .no-doctor {
    text-align: center;
    padding: 60rpx 0;
    color: #999;
    font-size: 28rpx;
  }
}

.date-scroll {
  white-space: nowrap;
  padding: 10rpx 0;

  .date-item {
    display: inline-block;
    width: 120rpx;
    padding: 15rpx 0;
    margin-right: 15rpx;
    border-radius: 8rpx;
    background: #f0f0f0;
    text-align: center;
    position: relative;

    &:last-child {
      margin-right: 0;
    }

    .week {
      display: block;
      font-size: 26rpx;
      margin-bottom: 5rpx;
    }

    .month-day {
      display: block;
      font-size: 28rpx;
      font-weight: 500;
    }

    .status {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: #f43f30;
      font-size: 24rpx;
      display: none;
    }

    &.active {
      background: #007aff;
      color: #fff;
    }

    &.disabled {
      opacity: 0.6;
      background: #f0f0f0;

      .month-day,
      .week {
        opacity: 0.5;
      }

      .status {
        display: block;
      }
    }
  }
}

.time-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;

  .time-item {
    padding: 25rpx 0;
    text-align: center;
    border-radius: 8rpx;
    background: #f0f0f0;
    font-size: 26rpx;
    transition: all 0.2s;

    &.active {
      background: #007aff;
      color: #fff;
      transform: scale(1.03);
    }

    &.disabled {
      opacity: 0.5;
      background: #f0f0f0;
      color: #999;
    }
  }
}

.time-note {
  text-align: center;
  padding: 30rpx 0;
  color: #f43f30;
  font-size: 26rpx;
}

.patient-list {
  .patient-item {
    padding: 20rpx;
    margin-bottom: 20rpx;
    border-radius: 8rpx;
    background: #f8f8f8;
    transition: all 0.3s;

    &:last-child {
      margin-bottom: 0;
    }

    &.active {
      background: #e3f2fd;
      border: 1rpx solid #007aff;
    }

    &-info {
      display: flex;
      flex-direction: column;

      .name {
        font-size: 30rpx;
        color: #333;
        margin-bottom: 8rpx;
        font-weight: 500;
      }

      .id-card {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.submit-btn {
  position: fixed;
  bottom: 30rpx;
  left: 30rpx;
  right: 30rpx;
  padding: 25rpx;
  background: #007aff;
  color: #fff;
  text-align: center;
  border-radius: 50rpx;
  font-size: 32rpx;
  font-weight: 500;
  box-shadow: 0 5rpx 15rpx rgba(0, 122, 255, 0.3);
  transition: all 0.3s;

  &.disabled {
    background: #ccc;
    color: #999;
    box-shadow: none;
    pointer-events: none;
  }

  &:active {
    transform: scale(0.98);
  }
}
</style>